<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px h-85%">
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="deviceCode"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'deviceName',
          children: 'children',
          class: customNodeClass,
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.deviceName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.deviceName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
       <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name">
            <component v-if="activeName === tab.name" :is="tab.component"  :currentNodeTask="currentNode"  :deviceTreeData="departmentList" :type="tab.type" />
          </el-tab-pane>
        </el-tabs>
      <!-- <Form
        :model="formTotalData"
        @register="formRegister"
        :schema="formSchema"
        :key="formKey"
      /> -->
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { ContentWrap } from "@/components/ContentWrap";
import { ref, unref, nextTick, watch, onMounted, reactive } from "vue";
import { ElTree } from "element-plus";
import { useForm } from "@/hooks/web/useForm";
import { Form, FormSchema } from "@/components/Form";
// 导入各个组件（请根据实际路径调整）
import DomesticComponents from '@/views/collectionTaskManagment/components/productDataManagement/domesticComponents/index.vue' //国产元器件
import ImportedComponents from '@/views/collectionTaskManagment/components/productDataManagement/importedComponents/index.vue' //进口元器件
import DomesticMaterials from '@/views/collectionTaskManagment/components/productDataManagement/domesticMaterials/index.vue' //国产材料
import ImportedMaterials from '@/views/collectionTaskManagment/components/productDataManagement/importedMaterials/index.vue' //进口材料
import DomesticMeProducts from '@/views/collectionTaskManagment/components/productDataManagement/domesticMeProducts/index.vue' // 国产机电产品
import ImportedMeProducts from '@/views/collectionTaskManagment/components/productDataManagement/importedMeProducts/index.vue' // 进口机电产品
import DomesticSoftware from '@/views/collectionTaskManagment/components/productDataManagement/domesticSoftware/index.vue' //国产软件
import ImportedSoftware from '@/views/collectionTaskManagment/components/productDataManagement/importedSoftware/index.vue' //进口软件
import type { DepartmentItem,DepartmentUserItem } from "@/components/DepartmentTree/types";

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => undefined
  },
});

// 主表单
const { formRegister, formMethods } = useForm();
const { setValues } = formMethods;
const currentNodeTask = ref({});
const currentNodeKey = ref("");
const departmentList = ref<DepartmentItem[]>([]);
// 添加formKey用于强制重新渲染表单
const formKey = ref(0);
const treeEl = ref<InstanceType<typeof ElTree> | null>(null); // 修改类型定义
const formTotalData =ref<DepartmentItem>()
const field2Value = ref("");
const missionCode = ref("");
// 修复：确保在组件挂载后再执行相关操作
const isMounted = ref(false);
const currentNode = ref();
// 修改自定义节点类，只对当前选中节点应用样式
const customNodeClass = (data: any, node: any) => {
  return node.isCurrent ? "is-current-node" : "";
};

const fetchDepartment = async (id: any) => {
  if (!id) return;
departmentList.value=[]
  try {
    const res = await `/api/mission/deviceTree/${id}/`.get();
    console.log(res);

    // res.data.map((item) => {
    //   item.children = [];
    // });
    departmentList.value.push(res.data) || [];



    // if (res.data.length > 0) {
      currentNodeKey.value = departmentList.value[0].deviceCode;
      currentNode.value ={ ...departmentList.value[0],missionCode:missionCode.value};

      // 确保组件已挂载后再设置当前节点
      if (isMounted.value && treeEl.value) {
        await nextTick();
        treeEl.value.setCurrentKey(currentNodeKey.value);

        // 触发当前节点的数据加载
        if (departmentList.value[0]) {
          currentChange(departmentList.value[0]);
        }
      }
    // }
  } catch (error) {
    console.error("获取部门数据失败:", error);
  }
};

const currentDepartment = ref("");
watch(
  () => currentDepartment.value,
  (val) => {
    if (treeEl.value) {
      treeEl.value.filter(val);
    }
  }
);

// 动态标签页配置
const tabs = ref([
  {
    label: '国产元器件',
    name: 'domesticComponents',
    component: shallowRef(DomesticComponents)
  },
  {
    label: '进口元器件',
    name: 'importedComponents',
    component: shallowRef(ImportedComponents)
  },
  {
    label: '国产材料',
    name: 'domesticMaterial',
    component: shallowRef(DomesticMaterials),
    type: 'domestic'
  },
  {
    label: '进口材料',
    name: 'importedMaterial',
    component: shallowRef(ImportedMaterials),
    type: 'imported'
  },
  {
    label: '国产机电产品',
    name: 'domesticElectromechanical',
    component: shallowRef(DomesticMeProducts),
    type: 'domestic'
  },
  {
    label: '进口机电产品',
    name: 'importedElectromechanical',
    component: shallowRef(ImportedMeProducts),
    type: 'imported'
  },
  {
    label: '国产软件',
    name: 'domesticSoftware',
    component: shallowRef(DomesticSoftware),
    type: 'domestic'
  },
  {
    label: '进口软件',
    name: 'importedSoftware',
    component: shallowRef(ImportedSoftware),
    type: 'imported'
  }
])

// 默认激活第一个标签
const activeName = ref(tabs.value[0].name)

const handleClick = (tab: TabsPaneContext, event: Event) => {

  currentNode.value =  currentNodeObj.value;
  // =
}



// 动态表单字段


const currentNodeObj = ref({});
const currentChange = async (data: any) => {

  if (!data) return;
console.log('missionCode.value',missionCode.value);

  currentNodeKey.value = data.deviceCode ;
  currentNode.value ={ ...data,missionCode:missionCode.value};
  currentNodeTask.value ={ ...data,missionCode:missionCode.value};
  currentNodeObj.value = { ...data,missionCode:missionCode.value};
  // field2Value.value = data.nodeType || "";

  // // 更新表单数据
  // formTotalData.value = { ...data };

  // // 设置表单值
  // await setFormValues(data);
};

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

// 修改 setFormValues 方法
const setFormValues = async (data: any) => {
  try {
    await nextTick(); // 等待下一个渲染周期

    const formData = {
      deviceName: data.deviceName || "",
      nodeType: data.nodeType || "",
      superiorSystem: data.superiorSystem || "",
      superiorSubsystem: data.superiorSubsystem || "",
      agreementNumber: data.agreementNumber || "",
      deviceModel: data.deviceModel || "",
      importantLevel: data.importantLevel || "",
      deviceCount: data.deviceCount || "",
      manufacturer: data.manufacturer || "",
      supervisorContact: data.supervisorContact || "",
      id: data.id || "",
    };

    // 设置字段值
    await setValues(formData);

    // 强制重新渲染表单
    formKey.value++;
  } catch (error) {
    console.error("设置表单值失败:", error);
  }
};

// 修复：监听 props.currentRow 的变化
watch(
  () => props.currentRow,
  (val) => {
    console.log('currentRow 变化123:', val);
    if (val && val.id) {
      missionCode.value = val.missionCode || "";
      fetchDepartment(val.id);
    }
  },
  { immediate: true, deep: true }
);

onMounted(async () => {
  isMounted.value = true;


});
</script>

<style scoped lang="less">
:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}

:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}
</style>
